#!/usr/bin/env python
# coding=utf-8

# File Name: pushData.py
# Author: Bill Zhang
# Mail: zchcandid@gmail.com 
# Created Time: Mon 28 Oct 2013 11:50:59 AM CST
import urllib.request  
import urllib.error
import hashlib
import simplejson as json
from imp import reload
#import os
#mongo connector
import pymongo
import linecache
#get the SessionKey
def getSession(c=1):
    if c is 1:
        reload(linecache)
        SessionKey=linecache.getline('SesKey',1).replace('\n','')
        return SessionKey
    url="http://183.62.107.205:9998/Security/RegisterUser/json/T0030" 
    pwd="ocs~rsh,uBZN"
    m = hashlib.md5(pwd.encode(encoding='utf-8'))  
    PassKey=m.hexdigest()
    #print(m.hexdigest())  
    #print(PassKey)
    #data=urllib.parse.urlencode(password) 

    PassKey=PassKey.encode(encoding='utf-8', errors = 'strict')
    #创建请求对象  
    req=urllib.request.Request(url,PassKey) 
    #获得服务器返回的数据  
    try:  
        response=urllib.request.urlopen(req) 
    except urllib.error.HTTPError as e:  
        print('Get SessionKey,Error code:',e.code)   
        return 404
    except urllib.error.URLError as e:  
        print('Reason',e.reason)  
        return 404
    sessionKey=response.read().decode('utf-8')
    SesKey=json.loads(sessionKey)
   # print(SesKey)
    #print(SesKey["Result"])
    if SesKey["ErrorCode"] is -103:
        print(SesKey["ErrorMessage"])
        return 404
    fileHandle = open ('SesKey','w') 
    fileHandle.write("%s" % SesKey["Result"]) 
    fileHandle.close() 
    return SesKey["Result"]
#
def saving(data):
    uri="mongodb://192.168.100.204:8888"
    try:
        con=pymongo.MongoClient(uri)
        db=con.icmall
        db.updatelog.insert(data)
    except pymongo.errors.ConnectionFailure:
        print("fail to connect mongodb,try after 3s")
        con=pymongo.MongoClient(uri)
    except pymongo.errors.ConfigurationError:
        print("Your password config is not right,fail to connect mongodb!")
        print("The formate should be 'mongodb://user:password@example.com/the_database'")
        print("Please try again!")
    except pymongo.errors.InvalidURI:
        print("Your uri is not write,fail to connect mongodb!")
        print("The formate should be 'mongodb://user:password@example.com/the_database'")
        print("Please try again!")
    except pymongo.errors.AutoReconnect(message='Lose connection,reconnect.....', errors=None):
        print("reconnect .......")
def pushing(PushData,k):
    id=PushData["ID"]
    SessionKey=getSession()
    URL="http://183.62.107.205:9998/ModifyData/OitsPrice/json/%s/N" % SessionKey
    PushData=[PushData]
    PushData=json.dumps(PushData)
    PushData=str(PushData).encode(encoding='utf-8', errors = 'strict')
    #创建请求对象  
    req1=urllib.request.Request(URL,PushData) 
    #获得服务器返回的数据  
    try:  
        response1=urllib.request.urlopen(req1) 
    except urllib.error.HTTPError as e:  
        print('Push data to bigDB,Error code:',e.code)   
        getSession(101)
        return 404
    except urllib.error.URLError as e:  
        print('Reason',e.reason)  
        return 404
    res=response1.read().decode('utf-8') 
    res=json.loads(res)
    print(res)
    if res['ErrorCode']==-101:
        print(res["ErrorMessage"])
        getSession(101)
        return 101
    res["ID"]=id
    #connect mongo for recording the log
    saving(res)
    return
if __name__=="__main__":
    """
    ---if __name=="__main__"-----
    This is for debug this moudle,
    When run this moudle as the main 
    the code below will run
    """
   # i=db.update.find()
